package Thread;


import java.util.concurrent.locks.*;

/**
 * 使用ReentrantLock + condition 打印ABAB
 */
public class ThreadDemo {
    private static Lock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();
    private static Condition conditionD = lock.newCondition();

    private static volatile Condition current = conditionA;

    public static void main(String[] args) throws Exception{
        ThreadDemo threadDemo = new ThreadDemo();
        int num = 3;
        Thread t1 = new Thread(() -> {
            printer(num, "A", conditionA, conditionB);
        });

        Thread t2 = new Thread(() -> {
            printer(num, "B", conditionB, conditionC);
        });

        Thread t3 = new Thread(() -> {
            printer(num, "C", conditionC, conditionD);
        });

        Thread t4 = new Thread(() -> {
            printer(num, "D", conditionD, conditionA);
        });
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t1.join();
        t2.join();
        t3.join();
        t4.join();

        Thread.yield();
    }

    public static void printer(int num, String name, Condition self, Condition next) {
        lock.lock();
        try {
            //获取到锁
            while (num > 0) {
                if (self != current) {
                    self.await();
                }
                System.out.print(name);
                current = next;
                num--;
                //打印完 唤醒下一个
                next.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
